import { app, BrowserWindow } from 'electron'
import path from 'path'
import { PNG } from 'pngjs'
import screenshot from 'screenshot-desktop'
import sharp from 'sharp'

export class EyedropperService {
  private win: BrowserWindow | null = null
  // private lastScreenshot: string | null = null // base64
  private captureWin: BrowserWindow | null = null

  // 1. 自动全屏截图，返回 base64 PNG
  async startRegionScreenshot(): Promise<string> {
    const shots = await screenshot.all()
    let buf: Buffer | null = null
    if (Array.isArray(shots) && shots.length > 0) {
      if (Buffer.isBuffer(shots[0])) {
        buf = Buffer.from(shots[0] as Buffer)
      } else if (typeof shots[0] === 'string') {
        buf = require('fs').readFileSync(shots[0] as string)
      } else if (
        shots[0] &&
        typeof shots[0] === 'object' &&
        'data' in shots[0] &&
        Buffer.isBuffer((shots[0] as any).data)
      ) {
        buf = Buffer.from((shots[0] as any).data)
      }
    }
    if (!buf) throw new Error('截图失败')
    const pngBuffer = await sharp(buf).png().toBuffer()
    const base64 = 'data:image/png;base64,' + pngBuffer.toString('base64')
    return base64
  }

  // 2. 根据 base64 PNG 和坐标获取像素颜色
  async getColorFromImage(base64: string, x: number, y: number): Promise<string | null> {
    const pngData = Buffer.from(base64.replace(/^data:image\/png;base64,/, ''), 'base64')
    const png = PNG.sync.read(pngData)
    if (x < 0 || y < 0 || x >= png.width || y >= png.height) return null
    const idx = (png.width * y + x) << 2
    const r = png.data[idx]
    const g = png.data[idx + 1]
    const b = png.data[idx + 2]
    return `#${((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1)}`
  }

  // 3. 弹窗显示截图图片，等待用户点击像素点
  openEyedropperWindow(base64: string) {
    if (this.win && !this.win.isDestroyed()) {
      this.win.focus()
      return
    }
    this.win = new BrowserWindow({
      width: 800,
      height: 600,
      resizable: true,
      alwaysOnTop: true,
      skipTaskbar: false,
      webPreferences: {
        nodeIntegration: true,
        contextIsolation: false,
        preload: path.join(__dirname, '../preload/index.js')
      }
    })
    const htmlPath = path.join(app.getAppPath(), 'src/main/eyedropper.html')
    this.win.loadFile(htmlPath)
    this.win.webContents.once('did-finish-load', () => {
      this.win?.webContents.send('eyedropper-show-image', base64)
    })
    this.win.on('closed', () => {
      this.win = null
    })
  }

  closeWindow() {
    if (this.win && !this.win.isDestroyed()) {
      this.win.close()
      this.win = null
    }
  }
}

export const eyedropperService = new EyedropperService()
